package com.atguigu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.StringUtils;
import com.atguigu.client.CartFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.CartInfo;
import com.atguigu.entity.OrderDetail;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.UserAddress;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.AuthContextHolder;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderInfoController {
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderInfoService orderService;
    @Autowired
    private UserFeignClient userFeignClient;

    //订单确认信息提供数据接口
    @GetMapping("/confirm")
    public RetVal<Map<String, Object>> confirm(HttpServletRequest request){
        //用户的收货地址列表
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> addressByUserId = userFeignClient.getAddressByUserId(userId);
        //购物车勾选的商品-送货清单
        List<CartInfo> selectedProductList = cartFeignClient.getSelectedProduct(userId);
        //订单总金额
        BigDecimal totalMoney = new BigDecimal(0);
        //商品总的数量
        int totaNum=0;
        //订单详情list
        ArrayList<OrderDetail> orderDetaiList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(selectedProductList)){
            for (CartInfo cartInfo : selectedProductList) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setSkuNum(cartInfo.getSkuNum()+"");
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setOrderPrice(cartInfo.getCartPrice());
                //计算总金额,multiply乘
                totalMoney=totalMoney.add(cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
                totaNum+=cartInfo.getSkuNum();
                orderDetaiList.add(orderDetail);
            }
        }
        Map<String, Object> retMap = new HashMap<>();
        //地址信息
        retMap.put("userAddressList",addressByUserId);
        //订单详情信息
        retMap.put("detailArrayList",orderDetaiList);
        //计算订单总金额
        retMap.put("totalMoney",totalMoney);
        //计算订单总数量
        retMap.put("totalNum",totaNum);
        //生成订单流水号
        String tradeNo=orderService.generateTradeNo(userId);
        retMap.put("tradeNo",tradeNo);
        return RetVal.ok(retMap);
    }

    //提交订单
    @PostMapping("/submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //返回无刷新不能重复提交订单
        String tradeNo = request.getParameter("tradeNo");
        boolean flag=orderService.checkTradeNo(tradeNo,userId);
        if(!flag){
            return RetVal.fail().message("不能无刷新回退提交订单");
        }
        //删除交易号
        orderService.deleteTradeNo(userId);
        //b.验证库存和价格
        List<String> warningInfoList = orderService.checkStockAndPrice(userId, orderInfo);
        //如果有警告信息
        if (warningInfoList.size()>0){
            return RetVal.fail().message(StringUtils.join(warningInfoList, ","));
        }
        //c保存订单信息
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId =orderService.saveOrderAndDetail(orderInfo);
        return RetVal.ok(orderId);
    }
    //3.根据订单id查询订单信息
    @GetMapping("/getOrderInfo/{orderId}")
        public OrderInfo getOrderInfo(@PathVariable Long orderId){
                return  orderService.getOrderInfo(orderId);
        }




    //拆单接口
    @RequestMapping("/splitOrder")
    public String splitOrder(@RequestParam Long orderId, @RequestParam String wareHouseIdSkuIdMapJson){
        return orderService.splitOrder(orderId,wareHouseIdSkuIdMapJson);
    }

    //保存订单基本信息与详情信息
    @RequestMapping("/saveOrderInfo")
    public Long saveOrderInfo(@RequestBody OrderInfo orderInfo){
        return orderService.saveOrderAndDetail(orderInfo);
    }
    }










